﻿#region 命名空间

using Sharp.Domain.PlatformBoundedContext.OrgModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.PermissionModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.UserModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.UserModule.Events;
using Sharp.Domain.Repositories;
using Sharp.Domain.Repository.EF;
using Sharp.Events;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Interfaces;
using Sharp.Infrastructure.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Sharp.Domain.PlatformBoundedContext.PersonModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.StoragerModule.Files;
using Sharp.Infrastructure.Model;
using System.Web;

#endregion

namespace Sharp.Domain.PlatformBoundedContext.UserModule.Services
{

    /// <summary>
    ///     表示用于Sharp领域模型中的领域服务类型。
    /// </summary>
    public partial class UserService : IUserService, IDataPermission
    {
        #region 私有字段

        private readonly IPermissionRepository _permissionRepository;
        private readonly IRepositoryContext _repositoryContext;
        private readonly IRoleRepository _roleRepository;
        private readonly IUserRepository _userRepository;
        private readonly IOrgRepository _orgRepository;
        private readonly IGroupRepository _groupRepository;

        #endregion

        #region 构造函数

        /// <summary>
        ///     初始化一个新的<c>UserService</c>类型的实例。
        /// </summary>
        /// <param name="repositoryContext">仓储上下文。</param>
        /// <param name="userRepository">用户仓储。</param>
        /// <param name="permissionRepository">权限仓储</param>
        /// <param name="roleRepository">角色仓储。</param>
        /// <param name="orgRepository"></param>
        /// <param name="groupRepository"></param>
        public UserService(IRepositoryContext repositoryContext,
            IUserRepository userRepository,
            IPermissionRepository permissionRepository,
            IRoleRepository roleRepository,
            IOrgRepository orgRepository,
            GroupRepository groupRepository)
        {
            _repositoryContext = repositoryContext;
            _userRepository = userRepository;
            _permissionRepository = permissionRepository;
            _roleRepository = roleRepository;
            _orgRepository = orgRepository;
            _groupRepository = groupRepository;
        }

        #endregion

        #region 用户



        #region 记录登录信息

        /// <inheritdoc />
        /// <summary>
        /// 记录登录信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Result<User> TryLogin(User user)
        {
            var res = new Result<User>();
            var ef = ((EntityFrameworkRepositoryContext)this._repositoryContext).Context;
            ef.Configuration.AutoDetectChangesEnabled = true;
            ef.Configuration.ProxyCreationEnabled = true;
            ef.Configuration.LazyLoadingEnabled = true;
            var info = _userRepository.Get(x => x.UserName == user.UserName, x => x.Roles);
            if (info == null)
            {
                res.Err = "用户不存在。";
                return res;
            }
            if (!user.Password.Sha1().Equals(info.Password, StringComparison.CurrentCultureIgnoreCase))
            {
                res.Err = "密码错误。";
                return res;
            }
            if (info.Profile != null && info.Profile.IsLockedOut)
            {
                res.Err = "用户已被锁定。";
                return res;
            }
            if (info.Profile != null && !info.Profile.IsApproved)
            {
                res.Err = "用户未审核。";
                return res;
            }
            EventBus.Instance.Publish(new LoginedEventData()
            {
                UserId = info.Id,
                LastLogonIp = user.LastLogonIp
            });


            if (!info.Permissions.Any())
            {
                res.Err = "未配置权限。";
                return res;
            }
            info.Face = SharpStorager.Context.Get(info.Face);

            ef.Configuration.AutoDetectChangesEnabled = false;
            ef.Configuration.LazyLoadingEnabled = false;

            res.Data = info;
            return res;
        }

        #endregion


        public IEnumerable<Permission> GetPermissionByUserName(string username)
        {
            var permissions = _permissionRepository.GetList(x => x.Users.Any(y => y.UserName == username));
            return permissions.ToList();
        }

        public IEnumerable<Permission> GetPermissionById(int id)
        {
            return _userRepository.Get(x => x.Id == id, x => x.Permissions).Permissions.ToList();
        }

        #endregion

        #region 保存权限

        /// <inheritdoc />
        /// <summary>
        ///     保存权限
        /// </summary>
        /// <param name="ids">权限Id</param>
        /// <param name="owner"></param>
        /// <param name="ownerId"></param>
        public Result SavePermission(IList<Guid> ids, string owner, int ownerId)
        {
            var res = new Result();


            var ef = _repositoryContext as IEntityFrameworkRepositoryContext;
            ef.Context.Configuration.ProxyCreationEnabled = true;
            ef.Context.Configuration.LazyLoadingEnabled = true;

            if (owner == "user")
            {
                var user = _userRepository.Get(ownerId, x => x.Permissions);
                if (user.Permissions.Any())
                {
                    user.Permissions.Clear();
                }

                _permissionRepository.GetList(x => ids.Contains(x.Id)).ToList().ForEach(item =>
                {
                    user.Permissions.Add(item);
                });

                _repositoryContext.Commit();
            }
            else
            {
                var role = _roleRepository.Get(ownerId);
                var oldPermissions = role.Permissions.Select(x => x.Id).ToArray();
                if (oldPermissions.Any())
                {
                    role.Permissions.Clear();
                }

                _permissionRepository.GetList(x => ids.Contains(x.Id)).ToList().ForEach(x =>
                {
                    role.Permissions.Add(x);
                });


                //角色下面的用户也保存一份
                role.Users.ToList().ForEach(u =>
                {
                    var userPermissions = u.Permissions.Select(p => p.Id).ToArray();
                    //u.Permissions.Clear();
                    //差集为角色授权之外用户独有的权限
                    var listResult = oldPermissions.Except(userPermissions).ToList();

                    var newIds = ids.Union(listResult).ToList();
                    _permissionRepository.GetList(x => newIds.Contains(x.Id)).ToList().ForEach(x =>
                    {
                        u.Permissions.Add(x);
                    });
                });



                _repositoryContext.Commit();
            }
            return res;
        }

        #endregion

        #region 将指定的用户赋予特定的角色。

        /// <inheritdoc />
        /// <summary>
        ///     将指定的用户赋予特定的角色。
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="roleId"></param>
        /// <returns>用以表述用户及其角色之间关系的实体。</returns>
        public Result AssignRole(int[] userIds, int roleId)
        {
            Result res = new Result();
            if (userIds == null)
            {
                res.Err = "用户数量不能为null";
                return res;
            }
            if (userIds.Length == 0)
            {
                res.Err = "用户数量不能为零";
                return res;
            }
            var list = _userRepository.GetList(ur => userIds.Contains(ur.Id)).ToList();

            list.ForEach(uc =>
            {
                uc.Roles.Add(_roleRepository.Get(r => r.Id == roleId));
            });

            _repositoryContext.Commit();

            return res;
        }

        #endregion



        #region 关联用户到角色

        /// <inheritdoc />
        /// <summary>
        /// 关联用户到角色
        /// </summary>
        /// <param name="userId1"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public Result RelationUser(int userId, int[] roleIds)
        {
            Result res = new Result();
            var ef = _roleRepository.Context as IEntityFrameworkRepositoryContext;
            ef.Context.Configuration.ProxyCreationEnabled = true;
            ef.Context.Configuration.LazyLoadingEnabled = true;


            var user = _userRepository.Get(x => x.Id == userId, r => r.Roles, x => x.Permissions);
            user.Roles?.Clear();
            var roles = _roleRepository.GetList(x => roleIds.Contains(x.Id));
            user.Roles = roles;

            user.Permissions.Clear();

            foreach (var r in roles)
            {
                user.Permissions = user.Permissions.Union(r.Permissions).Distinct().ToList();
            }


            return res;
        }

        #endregion


        #region 关联用户到工作组

        /// <summary>
        /// 关联用户到工作组
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public Result RelationUserForGroup(int groupId, int[] userIds)
        {
            Result res = new Result();
            var ef = _groupRepository.Context as IEntityFrameworkRepositoryContext;
            ef.Context.Configuration.ProxyCreationEnabled = true;
            ef.Context.Configuration.LazyLoadingEnabled = true;
            var group = _groupRepository.Get(x => groupId == (x.Id));
            if (group == null)
            {
                res.Err = "工作组不存在。";
                return res;
            }

            userIds.ToList().ForEach(x =>
            {
                var u = _userRepository.Get(x);
                u.Groups.Clear();
                u.Groups.Add(group);
            });

            _repositoryContext.Commit();
            return res;
        }

        #endregion


        /// <summary>
        /// 根据角色获取用户列表
        /// </summary>
        /// <param name="roleIDs">多个角色ID</param>
        /// <returns>用户列表</returns>
        public IList<User> GetUserListByRoles(int[] roleIDs)
        {
            return _userRepository.GetList(x => x.Roles.Any(y => roleIDs.Contains(y.Id)));
        }

        /// <summary>
        /// 根据接收者类型，来获取角色用户树的数据
        /// receiverType 参数说明
        /// 默认:0
        /// 上司:1
        /// 同事:2
        /// 下属:3
        /// </summary>
        /// <param name="roleIDs">角色ID</param>
        /// <param name="runnerUserId">用户ID</param>
        /// <param name="receiverType">接收者类型</param>
        /// <returns>用户列表</returns>
        public IList<User> GetUserListByRoleReceiverType(int[] roleIDs, string runnerUserId, int receiverType)
        {
            //默认取节点上定义的角色用户列表
            if (receiverType == 0)
                return GetUserListByRoles(roleIDs);
            else if (receiverType == 1)
                return GetSuperiorList(roleIDs, int.Parse(runnerUserId));
            else if (receiverType == 2)
                return GetCompeerList(roleIDs, int.Parse(runnerUserId));
            else if (receiverType == 3)
                return GetSubordinateList(roleIDs, int.Parse(runnerUserId));
            else return null;
        }

        /// <summary>
        /// 获取上司列表
        /// </summary>
        /// <param name="roleIDs">角色列表</param>
        /// <param name="curUserID">当前用户Id</param> 
        /// <returns>用户列表</returns>
        private List<User> GetSuperiorList(int[] roleIDs, int curUserID)
        {
            //var sql = @"SELECT 
            //                U.ID AS UserID,
            //                U.UserName
            //            FROM SysUser U
            //            INNER JOIN SysEmployeeManager EM
            //               ON U.ID = EM.MgrUserID
            //            INNER JOIN SysRoleUser RU
            //               ON U.ID = RU.UserID
            //            INNER JOIN @tblRoleIDS R
            //               ON R.ID = RU.RoleID
            //            WHERE EM.EmpUserID = @curUserID";
            //var userDbSet = session.GetRepository<UserEntity>().GetDbSet();
            //var roleUserDbSet = session.GetRepository<RoleUserEntity>().GetDbSet();
            //var empMgrDbSet = session.GetRepository<EmpMgrEntity>().GetDbSet();
            //var list = (from u in userDbSet
            //            join ru in roleUserDbSet on u.ID equals ru.UserID
            //            join em in empMgrDbSet on u.ID equals em.MgrUserID
            //            where em.EmpUserID == curUserID && roleIDs.Contains(ru.RoleID.ToString())
            //            select new User
            //            {
            //                UserID = u.ID.ToString(),
            //                UserName = u.UserName
            //            })
            //            .ToList();
            //return list;
            return new List<User>();
        }

        /// <summary>
        /// 获取同事列表
        /// </summary>
        /// <param name="roleIDs">角色列表</param>
        /// <param name="curUserID">当前用户Id</param>
        /// <returns>用户列表</returns>
        private List<User> GetCompeerList(int[] roleIDs, int curUserID)
        {
            //        var sql = @"SELECT 
            //	U.ID AS UserID,
            //	U.UserName
            //FROM SysUser U
            //INNER JOIN SysEmployeeManager EM
            //	ON U.ID = EM.EmpUserID
            //INNER JOIN SysRoleUser RU
            //    ON U.ID = RU.UserID
            //INNER JOIN @tblRoleIDS R
            //    ON R.ID = RU.RoleID
            //WHERE EM.MgrUserID IN
            //	(
            //		SELECT 
            //			MgrUserID
            //		FROM SysEmployeeManager
            //		WHERE EmpUserID = @curUserID
            //	)";
            //var userDbSet = session.GetRepository<UserEntity>().GetDbSet();
            //var roleUserDbSet = session.GetRepository<RoleUserEntity>().GetDbSet();
            //var empMgrDbSet = session.GetRepository<EmpMgrEntity>().GetDbSet();
            //var list = (from u in userDbSet
            //            join ru in roleUserDbSet on u.ID equals ru.UserID
            //            join em in empMgrDbSet on u.ID equals em.EmpUserID
            //            join em2 in empMgrDbSet on em.MgrUserID equals em2.MgrUserID
            //            where em2.EmpUserID == curUserID && roleIDs.Contains(ru.RoleID.ToString())
            //            select new User
            //            {
            //                UserID = u.ID.ToString(),
            //                UserName = u.UserName
            //            })
            //            .ToList();
            //return list;

            return new List<User>();
        }

        /// <summary>
        /// 获取下属列表
        /// </summary>
        /// <param name="roleIDs">角色列表</param>
        /// <param name="curUserID">当前用户Id</param>
        /// <param name="session">会话</param>
        /// <returns>用户列表</returns>
        private List<User> GetSubordinateList(int[] roleIDs, int curUserID)
        {
            //        var sql = @"SELECT 
            //	U.ID AS UserID,
            //	U.UserName
            //FROM SysUser U
            //INNER JOIN SysEmployeeManager EM
            //	ON U.ID = EM.EmpUserID
            //INNER JOIN SysRoleUser RU
            //    ON U.ID = RU.UserID
            //INNER JOIN @tblRoleIDS R
            //    ON R.ID = RU.RoleID
            //WHERE EM.MgrUserID = @curUserID";

            //var userDbSet = session.GetRepository<UserEntity>().GetDbSet();
            //var roleUserDbSet = session.GetRepository<RoleUserEntity>().GetDbSet();
            //var empMgrDbSet = session.GetRepository<EmpMgrEntity>().GetDbSet();
            //var list = (from u in userDbSet
            //            join ru in roleUserDbSet on u.ID equals ru.UserID
            //            join em in empMgrDbSet on u.ID equals em.EmpUserID
            //            where em.MgrUserID == curUserID && roleIDs.Contains(ru.RoleID.ToString())
            //            select new User
            //            {
            //                UserID = u.ID.ToString(),
            //                UserName = u.UserName
            //            })
            //            .ToList();
            //return list;

            return new List<User>();
        }

        #region 刷新用户授权数据

        /// <inheritdoc />
        /// <summary>
        /// 刷新用户授权数据
        /// </summary>
        /// <param name="userid"></param>
        public Result RefurbishUserPermissionData(int userid)
        {
            Result res = new Result();
            var ef = _roleRepository.Context as IEntityFrameworkRepositoryContext;
            ef.Context.Configuration.ProxyCreationEnabled = true;
            ef.Context.Configuration.LazyLoadingEnabled = true;

            var user = _userRepository.Get(x => x.Id == userid);
            if (user == null)
            {
                res.Err = "用户不存在。";
                return res;
            }

            var rolePermissions = new List<Permission>();
            user.Roles.ToList().ForEach(x =>
            {
                rolePermissions.AddRange(x.Permissions);
            });

            user.Permissions = user.Permissions.Union(rolePermissions.Distinct()).ToList();

            _roleRepository.Context.Commit();

            ef.Context.Configuration.LazyLoadingEnabled = false;
            ef.Context.Configuration.ProxyCreationEnabled = false;
            return res;
        }

        #endregion


        /// <summary>
        /// 数据权限，部门模式
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public IEnumerable<Guid?> GetDataPermissionForDev(Type entityType)
        {
            var ef = (_repositoryContext as EntityFrameworkRepositoryContext)?.Context;
            ef.Configuration.AutoDetectChangesEnabled = true;
            ef.Configuration.LazyLoadingEnabled = true;
            ef.Configuration.ProxyCreationEnabled = true;

            int? userId;
            if (HttpContext.Current == null)
            {
                return null;
            }
            userId = HttpContext.Current.User.Identity.GetUserId();
            if (userId.IsEmpty())
            {
                return new List<Guid?>();
            }

            var roles = _roleRepository.GetList(x => x.Users.Any(u => u.Id == userId)).ToList();
            if (roles == null)
            {
                throw new ArgumentNullException("用户不存在，或者数据有误。");
            }

            var authorizedOrgs = new List<Guid>();
            roles.ForEach(x =>
            {
                authorizedOrgs.AddRange(x.AuthorizedOrgs.Select(s => s.Id));
            });
            ef.Configuration.LazyLoadingEnabled = false;
            ef.Configuration.ProxyCreationEnabled = false;

            return authorizedOrgs.OfType<Guid?>();
        }

        /// <summary>
        /// 数据权限，个人模式
        /// </summary>
        /// <returns></returns>
        public IEnumerable<int?> GetDataPermissionForUser(Type entityType)
        {
            //根据Entity对象得到模块Id
            if (!DataPermissionConfig.Dictionary.TryGetValue(entityType, out var code))
            {
                return null;
            }
            int? userId;
            if (HttpContext.Current == null)
            {
                return null;
            }
            userId = HttpContext.Current.User.Identity.GetUserId();
            //刚刚登录时肯定会为空
            if (userId.IsEmpty())
            {
                return null;
            }

            var ef = (_repositoryContext as EntityFrameworkRepositoryContext)?.Context;
            ef.Configuration.LazyLoadingEnabled = true;
            ef.Configuration.ProxyCreationEnabled = true;

            var user = _userRepository.Get(userId.Value);
            if (user == null)
            {
                throw new ArgumentNullException("用户不存在，或者数据有误。");
            }

            IEnumerable<int?> output;

            //创建者可见
            var ownerScope = user.Permissions.Any(x => x.Code == $"{code}_OwnerScope");
            if (ownerScope)
            {
                output = new[] { userId, (int?)null };
            }
            else if (user.Permissions.Any(x => x.Code == $"{code}_GroupScope")) //同组可见
            {
                var someGroup = user.Groups.Select(x => x.Id).OfType<int?>();
                output = someGroup;
            }
            else //if (user.Permissions.Any(x => x.Code == $"{code}_PublicScope")) //全部可见 
            {
                output = null;
            }

            ef.Configuration.LazyLoadingEnabled = false;
            ef.Configuration.ProxyCreationEnabled = false;
            return output;
        }

        /// <summary>
        /// 更新权限库
        /// </summary>
        /// <param name="dtos"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public Result RefurbishAvailablePermissionData(IList<AvailablePermission> dtos, string columns)
        {
            var availablePermissionRepository = ServiceLocator.Instance.GetService<IAvailablePermissionRepository>();
            (availablePermissionRepository.Context as EntityFrameworkRepositoryContext)?.Context.Database
                .ExecuteSqlCommand("DELETE FROM Platform_AvailablePermissions");


            var data = new List<AvailablePermission>();
            for (var i = 0; i < dtos.Count; i++)
            {
                var x = dtos[i];

                if (x.Category == "01" && !x.IsShortcut)
                {
                    var maxOrderIndex = dtos.Where(p => p.ParentId == x.Id)
                        .DefaultIfEmpty(new AvailablePermission() { OrderIndex = -1 })
                        .Max(m => m.OrderIndex);

                    var rows = columns.Split(new[] { '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    if (rows.Any(c => c.Equals(x.Code + x.SystemCode)))
                    {
                        #region 数据列表

                        var dataList = new AvailablePermission()
                        {
                            Category = "02",
                            Code = x.Code + "_DataList",
                            Title = "数据列表",
                            ParentId = x.Id,
                            SystemCode = x.SystemCode
                        };
                        dataList.OrderIndex = ++maxOrderIndex;
                        dataList.Id = dataList.BuildId();
                        dtos.Add(dataList);


                        for (var index = 0; index < rows.Length - 1; index++)
                        {
                            if (rows[index].Equals(x.Code + x.SystemCode) && rows[index + 1].Contains(":"))
                            {
                                var fields = rows[index + 1].Split('&');
                                var itemOrder = 0;

                                for (var indexB = 0; indexB < fields.Length; indexB++)
                                {
                                    var dataListItem = new AvailablePermission()
                                    {
                                        Category = "03",
                                        Code = dataList.Code + "_" + fields[indexB].Split(':')[1],
                                        Title = fields[indexB].Split(':')[0],
                                        ParentId = dataList.Id,
                                        OrderIndex = ++itemOrder,
                                        SystemCode = x.SystemCode
                                    };
                                    dataListItem.Id = dataListItem.BuildId();
                                    dtos.Add(dataListItem);
                                }
                            }
                        }

                        #endregion
                    }

                    if (DataPermissionConfig.Dictionary.ContainsValue(x.Code))
                    {
                        #region 数据可见范围

                        var dataScope = new AvailablePermission()
                        {
                            Category = "04",
                            Code = x.Code + "_DataScope",
                            Title = "数据可见范围",
                            ParentId = x.Id,
                            SystemCode = x.SystemCode
                        };
                        dataScope.OrderIndex = ++maxOrderIndex;
                        dataScope.Id = dataScope.BuildId();
                        dtos.Add(dataScope);

                        var groupScope = new AvailablePermission()
                        {
                            Category = "06",
                            Code = x.Code + "_GroupScope",
                            Title = "同组可见",
                            ParentId = dataScope.Id,
                            SystemCode = x.SystemCode,
                            OrderIndex = 0
                        };
                        groupScope.Id = groupScope.BuildId();
                        dtos.Add(groupScope);

                        var ownerScope = new AvailablePermission()
                        {
                            Category = "05",
                            Code = x.Code + "_OwnerScope",
                            Title = "创建者可见",
                            ParentId = dataScope.Id,
                            SystemCode = x.SystemCode,
                            OrderIndex = 1
                        };
                        ownerScope.Id = ownerScope.BuildId();
                        dtos.Add(ownerScope);

                        var publicScope = new AvailablePermission()
                        {
                            Category = "07",
                            Code = x.Code + "_PublicScope",
                            Title = "所有人可见",
                            ParentId = dataScope.Id,
                            SystemCode = x.SystemCode,
                            OrderIndex = 2
                        };
                        publicScope.Id = publicScope.BuildId();
                        dtos.Add(publicScope);


                        #endregion
                    }

                    #region 列表操作

                    var oper = new AvailablePermission()
                    {
                        Category = "08",
                        Code = x.Code + "_Operation",
                        Title = "列表操作",
                        ParentId = x.Id,
                        SystemCode = x.SystemCode,
                        OrderIndex = ++maxOrderIndex
                    };
                    oper.Id = oper.BuildId();
                    dtos.Add(oper);

                    var modifiedLogobj = new AvailablePermission()
                    {
                        Category = "09",
                        Code = x.Code + "_ModifiedLog",
                        Title = "查看修改日志",
                        ParentId = oper.Id,
                        SystemCode = x.SystemCode,
                        OrderIndex = 0
                    };
                    modifiedLogobj.Id = modifiedLogobj.BuildId();
                    dtos.Add(modifiedLogobj);

                    var exportobj = new AvailablePermission()
                    {
                        Category = "09",
                        Code = x.Code + "_ExportToExcel",
                        Title = "导出",
                        ParentId = oper.Id,
                        SystemCode = x.SystemCode,
                        OrderIndex = 1
                    };
                    exportobj.Id = exportobj.BuildId();
                    dtos.Add(exportobj);


                    #endregion
                }

                data.Add(x);

            }


            availablePermissionRepository.Add(data);
            availablePermissionRepository.Context.Commit();



            return new Result();
        }


        /// <summary>
        /// 分配所有权限给超级管理员角色
        /// </summary>
        /// <returns></returns>
        public Result AllotAllPermissionToAdminRole()
        {
            var ef = (_repositoryContext as EntityFrameworkRepositoryContext)?.Context;
            ef.Configuration.LazyLoadingEnabled = true;
            ef.Configuration.ProxyCreationEnabled = true;
            ef.Database.ExecuteSqlCommand("Delete from Platform_Permissions");

            ef.Database.ExecuteSqlCommand(
                "INSERT INTO Platform_Permissions(Id,Code,Title,Category,ParentId,OrderIndex,Route,Ico,SystemCode,ModuleId) SELECT * FROM Platform_AvailablePermissions");
            ef.Database.ExecuteSqlCommand("delete from Platform_PermissionRole");

            ef.Database.ExecuteSqlCommand(
                "INSERT INTO Platform_PermissionRole (PermissionId ,RoleId) select P.Id,R.Id From Platform_Permissions P ,Platform_Roles R WHERE Name='超级管理员'");
            ef.Database.ExecuteSqlCommand("delete from Platform_PermissionUser");
            ef.Database.ExecuteSqlCommand(
                "INSERT INTO Platform_PermissionUser (PermissionId ,UserId) SELECT P.Id,U.Id From Platform_Permissions P,Platform_Users U where U.UserName='Admin'");

            return new Result();
        }

        /// <summary>
        /// 保存可用权限列表到权限列表
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Result AvailablePermissionToPermission(Guid[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return new Result() { Err = "传入的数据不能为空。" };
            }
            var ef = (_repositoryContext as EntityFrameworkRepositoryContext)?.Context.Database;

            //删除不存在的权限，其余的会级联删除
            ef.ExecuteSqlCommand("DELETE FROM Platform_Permissions WHERE Id NOT IN ('" + string.Join("','", ids) +
                                 "')");

            //新的权限数据
            var newIds = ids.Except(ef.SqlQuery<Guid>("SELECT Id FROM Platform_Permissions").ToList()).ToArray();

            if (newIds.Any())
                ef.ExecuteSqlCommand(
                    $"INSERT INTO Platform_Permissions select * from Platform_AvailablePermissions WHERE Id IN ('{string.Join("','", newIds)}')");

#if MSSQL
            ef.ExecuteSqlCommand(@"UPDATE A 
            SET
            A.[Code] = B.[Code]
                , A.[Title] = B.[Title]
                , A.[Category] = B.[Category]
                , A.[ParentId] = B.[ParentId]
                , A.[OrderIndex] = B.[OrderIndex]
                , A.[Route] = B.[Route]
                , A.[Ico] = B.[Ico]
                , A.[SystemCode] = B.[SystemCode]
                , A.[ModuleId] = B.[ModuleId]
            FROM Platform_Permissions A, Platform_AvailablePermissions B WHERE A.ID = B.ID");
#endif

            return new Result();
        }

        /// <summary>
        /// 保存组织结构数据权限
        /// </summary>
        /// <returns></returns>
        public Result SaveOrgPermission(Guid[] orgIds, int roleId)
        {
            var res = new Result();
            if (orgIds == null)
            {
                res.Err = "组织Id不能为空。";
                return res;
            }

            var ef = (_repositoryContext as EntityFrameworkRepositoryContext)?.Context;
            ef.Configuration.LazyLoadingEnabled = true;
            ef.Configuration.ProxyCreationEnabled = true;

            var role = _roleRepository.Get(roleId, x => x.AuthorizedOrgs);
            if (role == null)
            {
                res.Err = "角色不存在。";
                return res;
            }

            role.AuthorizedOrgs.Clear();

            role.AuthorizedOrgs = _orgRepository.GetList(x => orgIds.Contains(x.Id));

            role.Users.ToList().ForEach(u =>
            {
                u.AuthorizedOrgs = _orgRepository.GetList(x => orgIds.Contains(x.Id));
            });

            _roleRepository.Context.Commit();

            return res;
        }
    }
}